package com.haixiaoke.saas.repository.electronicVisa.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.haixiaoke.saas.repository.electronicVisa.pojo.ElectronicVisaContract;
import com.haixiaoke.saas.repository.pojo.ElectronicSigningContract;
import com.haixiaoke.saas.repository.pojo.OrgElectronicVisa;
import com.haixiaoke.saas.repository.electronicVisa.pojo.TencentCallbackMsgType;
import com.haixiaoke.saas.repository.electronicVisa.pojo.TencentElectronicVisaCallback;
import com.haixiaoke.saas.repository.service.IElectronicSigningContractService;
import com.haixiaoke.saas.repository.service.IOrgElectronicVisaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

/**
 * @author qixi
 * @date 2023/12/23
 */
@Service
@Slf4j
public class TencentCallbackService {

    @Autowired
    private IOrgElectronicVisaService orgElectronicVisaService;
    @Autowired
    private IElectronicSigningContractService electronicSigningContractService;



    @Transactional
    public void callback(TencentElectronicVisaCallback bean) {

        String msgType = bean.getMsgType();
        switch (msgType){
            case TencentCallbackMsgType.OPENE_VISA:
                this.openElectronicVisa(bean);
                break;
            case TencentCallbackMsgType.CONTRACT_SIGNING:
                this.contractSigning(bean);
                break;
            case TencentCallbackMsgType.BILLING_USE:
                this.billingUse(bean);
                break;
            default:
                break;
        }

        // todo 根据消息类型处理

        // todo 根据消息体处理
    }

    private void billingUse(TencentElectronicVisaCallback bean) {

        Map<String, Object> msgData = bean.getMsgData();
        String type = msgData.get("QuotaType").toString();
        // 企业版合同	CloudEnterprise
        if ("CloudEnterprise".equals(type)){
            Integer useCount = (Integer)msgData.get("UseCount");
            if (0 <= useCount){
                String flowId = msgData.get("FlowId").toString();
                ElectronicSigningContract electronicSigningContract = electronicSigningContractService.selectElectronicSigningContractByFlowId(flowId);
                Long orgId = electronicSigningContract.getOrgId();

                //  根据orgId查询企业信息
                OrgElectronicVisa orgElectronicVisa = orgElectronicVisaService.selectOrgElectronicVisaByOrgId(orgId);
                orgElectronicVisa.setContractUsedNumber(orgElectronicVisa.getContractUsedNumber() + useCount);
                orgElectronicVisaService.updateOrgElectronicVisa(orgElectronicVisa);
            }
        }

    }

    private void contractSigning(TencentElectronicVisaCallback bean) {

        Map<String, Object> msgData = bean.getMsgData();

        // 回调传入的合同数据
        String customerData = msgData.get("CustomerData").toString();
        ElectronicVisaContract contract = JSONUtil.toBean(customerData, ElectronicVisaContract.class);

        Long contractId = contract.getContractId();
        String flowStatus = msgData.get("FlowStatus").toString();
        log.info("合同签署回调：签署状态  {}", flowStatus);
        ElectronicSigningContract electronicSigningContract = electronicSigningContractService.selectElectronicSigningContractByContractId(contractId);
        Integer createOn = Convert.toInt(msgData.get("CreateOn"));
        Integer deadline = Convert.toInt(msgData.get("Deadline"));

        // 使用Hutool将Unix时间戳转为Java Date对象
        String createOnDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date(createOn * 1000));
        String deadlineDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date(deadline * 1000));
        electronicSigningContract.setContractCreateTime(Convert.toDate(createOnDate));
        electronicSigningContract.setContractCompletionTime(Convert.toDate(deadlineDate));
        // 合同签署完成
        if ("ALL".equals(flowStatus)){
            electronicSigningContract.setContractState(ElectronicSigningContract.CONTRACT_STATE_AWAIT_SIGN);
            electronicSigningContract.setUpdateTime(new Date());
            electronicSigningContractService.updateElectronicSigningContract(electronicSigningContract);
        }else if ("REJECT".equals(flowStatus)){
            electronicSigningContract.setContractState(ElectronicSigningContract.CONTRACT_STATE_SIGN_OK);
            electronicSigningContract.setUpdateTime(new Date());
        }
        electronicSigningContractService.updateElectronicSigningContract(electronicSigningContract);
    }

    private void openElectronicVisa(TencentElectronicVisaCallback bean) {

        Map<String, Object> msgData = bean.getMsgData();

        String proxyOrganizationOpenId = msgData.get("ProxyOrganizationOpenId").toString();
        String[] split = proxyOrganizationOpenId.split("_");
        String orgId = split[2];
        String orgName = split[0];
        OrgElectronicVisa orgElectronicVisa = new OrgElectronicVisa();
        orgElectronicVisa.setOrgId(Long.valueOf(orgId));
        orgElectronicVisa.setOrgName(orgName);
        orgElectronicVisa.setApplicationId(msgData.get("ApplicationId").toString());
        orgElectronicVisa.setProxyOrganizationOpenId(msgData.get("ProxyOrganizationOpenId").toString());
        orgElectronicVisa.setProxyOperatorOpenid(msgData.get("ProxyOperatorOpenid").toString());
        orgElectronicVisa.setOrganizationName(msgData.get("OrganizationName").toString());
        orgElectronicVisa.setUSCC(msgData.get("USCC").toString());
        orgElectronicVisa.setCreateTime(new Date());
        orgElectronicVisaService.insertOrgElectronicVisa(orgElectronicVisa);

    }
}
